package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.service.storage.Oss;
import com.microtf.inscription.framework.service.storage.StorageException;
import com.microtf.inscription.framework.vo.blog.PostVo;
import com.microtf.inscription.framework.vo.storage.StorageObjectVo;
import com.microtf.inscription.jpa.entity.BlogCategory;
import com.microtf.inscription.jpa.entity.BlogPost;
import com.microtf.inscription.jpa.entity.BlogSpace;
import com.microtf.inscription.metaweblog.MetaWebLogListener;
import com.microtf.inscription.metaweblog.vo.Blog;
import com.microtf.inscription.metaweblog.vo.Category;
import com.microtf.inscription.metaweblog.vo.FileData;
import com.microtf.inscription.metaweblog.vo.Post;
import com.microtf.inscription.metaweblog.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.util.DigestUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * MetaWebLogListener的一个框架默认实现
 *
 * @author guliuzhong
 * @see MetaWebLogListener
 */
public class BlogMetaWebLogListener implements MetaWebLogListener {
    UserService userService;
    BlogService blogService;


    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    Oss oss;

    @Autowired
    public void setOss(Oss oss) {
        this.oss = oss;
    }

    @Override
    public String getRequestUrl() {
        return null;
    }

    @Override
    public String getHomePageUrl() {
        return null;
    }

    @Override
    public Boolean getEnable() {
        return true;
    }

    @Override
    public List<Blog> getBlogs(User user) {
        List<BlogSpace> blogSpace = blogService.getBlogSpace(Long.valueOf(user.getUserId()));
        return blogSpace.stream().map(item ->
                Blog.builder().blogId(item.getSpaceId().toString()).blogName(item.getBlogName()).build()
        ).collect(Collectors.toList());
    }

    @Override
    public Post editPost(Blog blog, Post post) {
        PostVo postVo = new PostVo();
        postVo.setAuthorId(Long.valueOf(post.getUser().getUserId()));
        postVo.setCatNames(post.getCategories());
        postVo.setCont(post.getDescription());
        postVo.setCreateDate(post.getDateCreated());
        if (post.getPostId() != null) {
            postVo.setPostId(Integer.valueOf(post.getPostId()));
        }
        postVo.setState(post.getPublish() ? "publish" : "draft");
        postVo.setTitle(post.getTitle());
        if (postVo.getPostId() == null) {
            postVo.setBlogSpaceId(Integer.valueOf(blog.getBlogId()));
        }
        BlogPost save = blogService.save(postVo);
        post.setPostId(String.valueOf(save.getPostId()));
        return post;
    }

    @Override
    public List<Post> getRecentPosts(Blog blog, int pageSize, User user) {
        Optional<BlogSpace> blogSpaceById = blogService.getBlogSpaceById(Integer.valueOf(blog.getBlogId()));
        if (!blogSpaceById.isPresent()) {
            return Collections.emptyList();
        }
        BlogSpace blogSpace = blogSpaceById.get();
        com.microtf.inscription.jpa.entity.User user1 = userService.getUser(user.getUsername());
        if (pageSize >= 100) {
            pageSize = 100;
        }
        if (pageSize <= 0) {
            pageSize = 50;
        }
        Page<BlogPost> postId = blogService.getPostBySpaceAndUser(1, Sort.by(new Sort.Order(Sort.Direction.DESC, "postId")), pageSize, blogSpace, user1);
        return postId.get().map(item -> {
            Post post = new Post();
            post.setPostId(item.getPostId().toString());
            String[] strings = item.getCategories().stream().map(BlogCategory::getTitle).toArray(String[]::new);
            post.setCategories(strings);
            post.setTitle(item.getTitle());
            post.setDateCreated(item.getDateCreated());
            post.setPublish("publish".equals(item.getState()));
            User.UserBuilder builder = User.builder();
            builder.userId(item.getAuthor().getId().toString());
            builder.username(item.getAuthor().getUsername());
            post.setUser(builder.build());
            post.setDescription(item.getBlogPostCont().getCont());
            return post;
        }).collect(Collectors.toList());
    }

    @Override
    public Optional<Post> getPost(String postId, User user) {
        Optional<BlogPost> blogPost = blogService.getBlogPost(Integer.valueOf(postId));
        if (blogPost.isPresent()) {
            BlogPost blogPost1 = blogPost.get();
            long aLong = Long.parseLong(user.getUserId());
            if (aLong == blogPost1.getAuthor().getId()) {
                return blogPost.map(item -> {
                    Post post = new Post();
                    post.setPostId(item.getPostId().toString());
                    String[] strings = item.getCategories().stream().map(BlogCategory::getTitle).toArray(String[]::new);
                    post.setCategories(strings);
                    post.setTitle(item.getTitle());
                    post.setDateCreated(item.getDateCreated());
                    post.setPublish("publish".equals(item.getState()));
                    User.UserBuilder builder = User.builder();
                    builder.userId(item.getAuthor().getId().toString());
                    builder.username(item.getAuthor().getUsername());
                    post.setUser(builder.build());
                    post.setDescription(item.getBlogPostCont().getCont());
                    return post;
                });
            }
        }
        return Optional.empty();
    }

    @Override
    public void deletePost(String postId, User user) {
        blogService.deleteBlog(Integer.valueOf(postId));
    }

    @Override
    public List<Category> getCategory(Blog blog, User user) {
        Optional<BlogSpace> blogSpaceById = blogService.getBlogSpaceById(Integer.valueOf(blog.getBlogId()));
        if (!blogSpaceById.isPresent()) {
            return Collections.emptyList();
        }
        BlogSpace blogSpace = blogSpaceById.get();
        return blogService.getAllCategory(blogSpace, 1, 1000).map(item -> {
            Category category = new Category();
            category.setCategoryId(item.getCategoryId().toString());
            category.setTitle(item.getTitle());
            category.setDescription(item.getTitle());
            return category;
        }).stream().collect(Collectors.toList());
    }

    @Override
    public String newMediaObject(Blog blog, User user, FileData fileData) {
        String s = DigestUtils.md5DigestAsHex(fileData.getBase64Bits());
        StorageObjectVo put = null;
        try {
            put = oss.put(fileData.getBase64Bits(), s);
        } catch (StorageException e) {
            e.printStackTrace();
        }
        return put.getUrl();
    }

    @Override
    public Optional<User> login(String username, String password) {
        Optional<com.microtf.inscription.jpa.entity.User> user = userService.validPassword(username, password);
        return user.map(item -> User.builder().userId(item.getId().toString()).username(item.getUsername()).build());
    }
}
